package com.ruoyi.oto.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.framework.web.service.MemberLoginService;
import com.ruoyi.common.core.domain.entity.MemberUser;
import com.ruoyi.oto.constants.MemberRoleConstant;
import com.ruoyi.oto.constants.YesNoFlag;
import com.ruoyi.oto.domain.MemberUserRole;
import com.ruoyi.oto.domain.vo.LoginVO;
import com.ruoyi.oto.service.MemberUserService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.tomcat.Jar;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 小程序-会员微信登陆
 */
@RestController
@RequestMapping("/api/v2/wechat")
@Slf4j
public class WechatController {

    @Autowired
    private WxMaService wxMaService;

    @Autowired
    private MemberLoginService memberLoginService;
    /**
     * 会员服务
     */
    @Autowired
    private MemberUserService memberUserService;

    @ApiOperation(value = "通过code注册并获取token")
    @ApiImplicitParams({@ApiImplicitParam(name = "code", value = "微信code", dataTypeClass = String.class, required = true),})
    @GetMapping("weChatRegister")
    public AjaxResult<LoginVO> weChatRegister(HttpServletRequest httpServletRequest,@RequestParam("code") String code) {
        log.info("当前返回code:{}", code);
        try {
            WxMaJscode2SessionResult result = wxMaService.getUserService().getSessionInfo(code);
            log.info("微信回调:{}", JSONUtil.toJsonStr(result));
            String openId = result.getOpenid();
            if (openId == null) {
                return AjaxResult.error("微信登录失败");
            }
            //根据openId获取登录用户信息
            MemberUser memberUser = memberUserService.getByOpendid(openId);
            if (memberUser == null) {
                //注册新用户
                memberUser = new MemberUser();
                memberUser.setOpenId(openId);
                memberUser.setNickName("未设置");
                memberUser.setLoginIp(httpServletRequest.getRemoteAddr());
                memberUser.setLastLoginTime(new Date());
                memberUser.setStatus(YesNoFlag.NO);  //正常
                memberUser.setDelFlag(YesNoFlag.NO);
                memberUser.setEnableFlag(YesNoFlag.YES);
                memberUser.setRoleId(MemberRoleConstant.游客);
                memberUser.setRoleName("游客");
                memberUserService.save(memberUser);
            }
            String token = memberLoginService.login(memberUser);
            LoginVO loginVO = new LoginVO();
            loginVO.setToken(token);
            loginVO.setMemberId(memberUser.getId().toString());
            log.info(JSONUtil.toJsonStr(AjaxResult.success(loginVO)));
            return AjaxResult.success(loginVO);
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取用户的手机号
     * @param code
     * @return
     */
    @ApiOperation(value = "通过code获取用户的手机号码信息")
    @ApiImplicitParams({@ApiImplicitParam(name = "code", value = "微信code", dataTypeClass = String.class, required = true),})
    @GetMapping("getUserPhone")
    public AjaxResult<WxMaPhoneNumberInfo> getUserPhone(@RequestParam("code") String code) {
        try {
            WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(code);
            return AjaxResult.success(phoneNoInfo);
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }
    }
}
